package cn.tedu.floristshop.controller;

import cn.tedu.floristshop.mapper.UserMapper;
import cn.tedu.floristshop.pojo.dto.UserLoginDTO;
import cn.tedu.floristshop.pojo.dto.UserRegDTO;
import cn.tedu.floristshop.pojo.entity.User;
import cn.tedu.floristshop.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println ("userRegDTO = " + userRegDTO);

        UserVO userVO = mapper.selectByPhone (userRegDTO.getPhone ());
        if (userVO!=null){
            return 2;//用户名已存在
        }
        User u =new User ();
        BeanUtils.copyProperties (userRegDTO,u);
        mapper.insert (u);
        return 1;
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        UserVO userVO = mapper.selectByPhone (userLoginDTO.getPhone ());
        if (userVO!=null){
            if (userVO.getPassword().equals(userLoginDTO.getPassword ())){
                //把登录成功的UserVO保存到  当前客户端对应的会话对象里面
                session.setAttribute ("user",userVO);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        //从当前客户端对应的会话对象里面取出登录的UserVO
        UserVO user = (UserVO)session.getAttribute("user");
        //如果登录过返回user对象  未登录返回null  但是经过JSON字符串转换后到客户端为空字符串
        return user;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute ("user");
    }
}

